﻿/************************************\
 *   ___                            *
 *  /                          /    *
 * (___ |  ___  ___       ___ (___  *
 * |    | |   )|___)| / )|___)|   ) *
 * |    | |    |__  |/|/ |__  |__/  *
 *                                  *
 * FireWeb    C# OpenSource Browser *
\************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Resources;
using System.Globalization;
using System.Reflection;
using System.IO;

namespace FireWeb.Pages
{
    public partial class Web : Form
    {
        [DllImport("user32.dll")]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        private Pipe.Client Client = new Pipe.Client();
        private Process MainThread;
        private int MyID;

        private ResourceManager LangManager;
        private CultureInfo Culture;

        public Web(int MainPID, string PipeName, int ID)
        {
            InitializeComponent();

            // Language Loading
            Culture = new CultureInfo(Properties.Settings.Default.Language);
            LangManager = new ResourceManager("FireWeb.Languages.Resources", Assembly.GetExecutingAssembly());

            newTabToolStripMenuItem.Text = LangManager.GetString("NewTab", Culture);

            Client.MessageReceived += Client_ProcessPacket;
            Client.ServerDisconnected += Client_ServerDisconnected;
            Client.Connect(PipeName);

            MainThread = Process.GetProcessById(MainPID);
            MyID = ID;

            Browser.Navigate(Properties.Settings.Default.Home);
            Browser.UserAgent += " FireWeb/1.0.0.0";
        }

        #region Client Voids
        void Client_ProcessPacket(byte[] message)
        {
            Invoke(new Pipe.Client.MessageReceivedHandler(ProcessPacket),
                new object[] { message });
        }

        void ProcessPacket(byte[] message)
        {
            ASCIIEncoding encoder = new ASCIIEncoding();
            string str = encoder.GetString(message, 0, message.Length);
            MessageBox.Show(str);
        }

        void Client_ServerDisconnected()
        {
            //Invoke(new Pipe.Client.ServerDisconnectedHandler(EnableStartButton));
            //MessageBox.Show("Oops! C'è qualche problema con FireWeb, prova a riavviare il programma :D");
        }

        void SendMessage(string Text)
        {
            ASCIIEncoding encoder = new ASCIIEncoding();
            byte[] messageBuffer = encoder.GetBytes(Text);
            Client.SendMessage(messageBuffer);
        }
        #endregion

        #region Browser Events
        private void URLBox_Enter(object sender, EventArgs e)
        {
            URLBox.SelectAll();
            OnURLBox = true;
            GetComboBox();
        }

        private void URLBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
            {
                if (!URLBox.Text.Contains("http") || !URLBox.Text.Contains("https"))
                {
                    Browser.Navigate("http://www.google.com/search?q=" + URLBox.Text);
                }
                else
                {
                    Browser.Navigate(URLBox.Text);
                }
                e.Handled = true;
            }
            else
            {
                OnURLBox = true;
                GetComboBox();
            }
        }

        private void Browser_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            SendMessage("webtabprogress" + Convert.ToChar(1) + e.ProgressPercentage.ToString());
        }

        private void Browser_DocumentTitleChanged(object sender, EventArgs e)
        {
            this.Text = Browser.DocumentTitle;
            SendMessage("tabtitle" + Convert.ToChar(1) + MyID + Convert.ToChar(1) + Browser.DocumentTitle);
        }

        private void Browser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            URLBox.Text = Browser.Url.ToString();

            SendMessage("favicon" + Convert.ToChar(1) + MyID + Convert.ToChar(1) + "default");
            Favicon.Image = global::FireWeb.Properties.Resources.favicon;

            WebIcon.Image = global::FireWeb.Properties.Resources.web;
            WebIcon.Visible = false;
            URLBox.Location = new Point(164, 9);

            // HTTPS Check
            if (IsHTTPS())
            {
                ShowHTTPS();
            }
        }

        private void Browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            // Favicon
            bool FavOK = false;
            string FaviconURL = null;
            try
            {
                WebKit.DOM.NodeList test = Browser.Document.GetElementsByTagName("link");
                foreach (WebKit.DOM.Element Element in test)
                {
                    if (Element.GetAttribute("rel") == "shortcut icon" || Element.GetAttribute("rel") == "icon")
                    {
                        FaviconURL = Element.GetAttribute("href");
                        Favicon.Image = Image.FromStream(System.Net.FileWebRequest.Create(FaviconURL).GetResponse().GetResponseStream());
                        FavOK = true;
                    }
                }

                if (!FavOK)
                {
                    string WEBURL = null;
                    string[] host = Browser.Url.ToString().Split(Convert.ToChar("/"));
                    int lastn = host.Length - 2;
                    for (int i = 2; i <= lastn; i++)
                    {
                        WEBURL += host[i] + "/";
                    }
                    Favicon.Image = Image.FromStream(System.Net.FileWebRequest.Create("http://" + WEBURL + "favicon.ico").GetResponse().GetResponseStream());
                    FaviconURL = "http://" + WEBURL + "favicon.ico";
                    FavOK = true;
                }

                SendMessage("favicon" + Convert.ToChar(1) + MyID + Convert.ToChar(1) + FaviconURL);
            }
            catch { SendMessage("favicon" + Convert.ToChar(1) + MyID + Convert.ToChar(1) + "default"); }

            Update_BTN.Visible = true;
            Cancel_BTN.Visible = false;
        }
        #endregion

        #region Browser Voids
        private void Favicon_Click(object sender, EventArgs e)
        {
            ShowInformation();
        }

        void ShowInformation()
        {

        }

        bool IsHTTPS()
        {
            string Type = Browser.Url.ToString().Split(Convert.ToChar(":"))[0];
            if (Type == "https")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        void ShowHTTPS()
        {
            //StatusText.Text = "HTTPS";
            WebIcon.Image = global::FireWeb.Properties.Resources._lock;
            WebIcon.Visible = true;

            URLBox.Location = new Point(185, 9); //164; 9
        }
        #endregion

        private void Web_Click(object sender, EventArgs e)
        {
            //SetForegroundWindow(MainThread.MainWindowHandle);
        }

        #region Buttons
        private void NewTab_Button_Click(object sender, EventArgs e)
        {
            SendMessage("newwebtab");
        }

        private void Settings_Button_Click(object sender, EventArgs e)
        {
            //SendMessage("websource" + Convert.ToChar(1) + Browser.Url);
            Point ButtonPos = Settings_Button.PointToScreen(new Point(0, 0));
            SettingsMenu.Show(ButtonPos.X - SettingsMenu.Size.Width + 40, ButtonPos.Y + 28);
        }

        private void Home_Button_Click(object sender, EventArgs e)
        {
            Browser.Navigate(Properties.Settings.Default.Home);
        }

        private void Forward_Button_Click(object sender, EventArgs e)
        {
            Browser.GoForward();
        }

        private void Back_Button_Click(object sender, EventArgs e)
        {
            Browser.GoBack();
        }
        #endregion

        private void newTabToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SendMessage("newwebtab");
        }

        private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Browser.ShowPrintDialog();
        }

        private void savePageWithNameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog SavePage = new SaveFileDialog();
                SavePage.Filter = "Only HTML File|*.html|HTML File and Resources|*.html";
                SavePage.ShowDialog();
                TextWriter Page = new StreamWriter(SavePage.FileName);
                Page.Write(Browser.DocumentText);
            }
            catch { }
        }

        private void Browser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            OnURLBox = false;
            HTTPCombo.Visible = false;

            Update_BTN.Visible = false;
            Cancel_BTN.Visible = true;
        }

        bool OnURLBox = false;
        private void URLBox_TextChanged(object sender, EventArgs e)
        {
            GetComboBox();
        }

        void GetComboBox()
        {
            if (OnURLBox && URLBox.Text != "")
            {
                HTTPCombo.Visible = true;
                HTTPCombo.Items.Clear();
                HTTPCombo.Items.AddRange(new string[] { "Search result", "Search " + URLBox.Text + " with Google" });
            }
            else
            {
                OnURLBox = false;
                HTTPCombo.Visible = false;
            }
        }

        private void URLBox_Leave(object sender, EventArgs e)
        {
            OnURLBox = false;
            HTTPCombo.Visible = false;
        }

        private void HTTPCombo_Enter(object sender, EventArgs e)
        {
            OnURLBox = true;
            HTTPCombo.Visible = true;
        }

        private void HTTPCombo_Click(object sender, EventArgs e)
        {
            OnURLBox = false;
            HTTPCombo.Visible = false;

            if (HTTPCombo.SelectedItem == HTTPCombo.Items[HTTPCombo.Items.Count - 1])
            {
                Browser.Navigate("http://www.google.com/search?q=" + URLBox.Text);
            }
        }

        private void Browser_Error(object sender, WebKit.WebKitBrowserErrorEventArgs e)
        {
            MessageBox.Show(e.Description);
        }

        private void Update_BTN_Click(object sender, EventArgs e)
        {
            Browser.Reload();
            //Update_BTN.Visible = false;
            //Cancel_BTN.Visible = true;
        }

        private void Cancel_BTN_Click(object sender, EventArgs e)
        {
            Browser.Stop();
            Update_BTN.Visible = true;
            Cancel_BTN.Visible = false;
        }
    }
}
